/*
 * @Description: 描述信息
 * @Version: 版本号
 * @Author: xuebao
 * @Date: 2023-12-14 12:35:28
 * @LastEditors: xuebao
 * @LastEditTime: 2023-12-14 14:45:56
 */
import { IDetailProp } from '@/types/modal'
import api from '@/api/orderApi'
import { Modal } from 'antd'
import { useImperativeHandle, useState } from 'react'
import { Order } from '@/types/api'
import { message } from '@/utils/AntdGlobal'
export default function OrderMarker(props: IDetailProp) {
  const [visible, setVisible] = useState(false)
  const [orderId, setOrderId] = useState('')
  const [markers, setMarkers] = useState<{ lng: string; lat: string; id: number }[]>([])
  useImperativeHandle(props.mRef, () => {
    return {
      open,
    }
  })
  //弹框
  const open = async (orderId: string) => {
    setOrderId(orderId)
    setVisible(true)
    const detail = await api.getOrderDetail(orderId)
    renderMap(detail)
  }

  //渲染地图
  const renderMap = (detail: Order.OrderItem) => {
    const map = new window.BMapGL.Map('markMap')
    map.centerAndZoom(detail.cityName, 12)
    var scaleCtrl = new window.BMapGL.ScaleControl()
    map.addControl(scaleCtrl)
    var zoomCtrl = new window.BMapGL.ZoomControl()
    map.addControl(zoomCtrl)
    map.enableScrollWheelZoom() //缩放轮
    //回显示
    detail.route.map((item) => {
      createMarker(map, item.lng, item.lat)
    })

    //绑定事件
    map.addEventListener('click', function (e: any) {
      createMarker(map, e.latlng.lng, e.latlng.lat)
    })
  }
  //创建marker
  const createMarker = (map: any, lng: string, lat: string) => {
    const id = Math.random() //生成一个随机数
    const marker = new window.BMapGL.Marker(new window.BMapGL.Point(lng, lat)) // 创建标注
    markers.push({ lng, lat, id })

    marker.id = id
    //给marker绑定一个删除
    const markerMenu = new window.BMapGL.ContextMenu()
    markerMenu.addItem(
      new window.BMapGL.MenuItem('删除', () => {
        map.removeOverlay(marker)
        const index = markers.findIndex((item) => item.id === marker.id)
        markers.splice(index, 1)
        setMarkers([...markers]) //删除成功以后需要立马保存
      }),
    )
    setMarkers([...markers]) //删除成功以后需要立马保存
    marker.addContextMenu(markerMenu)
    map.addOverlay(marker) // 将标注添加到地图中
  }
  //提交打点
  const handleSubmit = async () => {
    await api.updateOrderInfo({
      orderId,
      route: markers,
    })
    handleCancel()
    message.success('打点成功')
  }
  //取消
  const handleCancel = () => {
    setVisible(false)
    setMarkers([])
  }
  return (
    <Modal
      title='地图打点'
      width={1100}
      open={visible}
      onOk={handleSubmit}
      onCancel={handleCancel}
      okText='确定'
      cancelText='取消'
    >
      <div id='markMap' style={{ height: 500 }}>
        地图打点
      </div>
    </Modal>
  )
}
